<template>
  <div class="recording_container">
    <h2 class="title">脚本录制</h2>
    <el-divider></el-divider>
    <el-timeline class="recorder_messages">
      <el-timeline-item
        v-for="(message, index) in messages"
        :key="index"
        :timestamp="formatTime(message.timestamp)"
      >
        {{ message.message }}
      </el-timeline-item>
    </el-timeline>
    <el-divider></el-divider>
    <div class="action_container">
      <el-button
        @keydown.space.prevent
        @keydown.enter.prevent
        class="action_button"
        :type="state === 'PAUSE' ? 'primary' : 'danger'"
        :icon="state === 'PAUSE' ? VideoPlay : VideoPause"
        @click="handleToggle"
      >
        {{ state === 'PAUSE' ? '开始' : '停止' }}({{ hotkeyLabel }})
      </el-button>
      <el-button
        class="action_button"
        type="success"
        :icon="Folder"
        @click="handleSave"
        :disabled="state != 'PAUSE' || recordSize === 0"
        >保存脚本</el-button
      >
    </div>
  </div>
</template>

<script setup>
import { inject, ref, onMounted, onUnmounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
// 导入需要全局注册的图标
import { VideoPlay, VideoPause, Folder } from '@element-plus/icons-vue'
import request from '@/utils/request.js'

const hotkeyLabel = ref('F10')

onMounted(async () => {
  const res = await request.get(`/setting/name/record.toggle`)
  hotkeyLabel.value = res.data.key
})

const handleToggle = async () => {
  request.post('/record/record/toggle')
}

const handleSave = async () => {
  try {
    const { value } = await ElMessageBox.prompt('请输入脚本名称', '提示', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      inputPattern: /\S+/, // 简单非空校验
      inputErrorMessage: '脚本名称不能为空',
    })

    // 发送POST请求到后端
    const response = await request.post('/record/save', {
      scriptName: value,
    })

    // 请求成功处理
    if (response.code === 0) {
      ElMessage({
        type: 'success',
        message: `脚本 ${value} 保存成功！`,
      })
    } else {
      ElMessage({
        type: 'error',
        message: '保存失败: ' + (response.data.message || '未知错误'),
      })
    }
  } catch (error) {
    // 区分取消输入和请求错误
    if (error === 'cancel' || error === 'close') {
      ElMessage({
        type: 'info',
        message: '已取消输入',
      })
    } else {
      console.error('保存出错:', error)
      ElMessage({
        type: 'error',
        message: '保存失败，请检查网络连接或联系管理员',
      })
    }
  }
}
const handleReset = async () => {
  if (isRunning.value) {
    ElMessage({
      type: 'warning',
      message: '请先停止录制',
    })
    return
  }
  const res = request.post('/record/reset')
}

const formatTime = (millis) => {
  // 将输入值转为数值型（防御性处理）
  const ms = Math.abs(Number(millis) || 0)
  // 分解时间单位
  const hours = Math.floor(ms / 3600000)
  const minutes = Math.floor((ms % 3600000) / 60000)
  const seconds = Math.floor((ms % 60000) / 1000)
  const remainingMs = ms % 1000
  // 格式化各部分（补零处理）
  const pad = (n, length) => String(n).padStart(length, '0')
  return [
    pad(hours, 2), // 小时两位数
    pad(minutes, 2), // 分钟两位数
    pad(seconds, 2), // 秒两位数
    pad(remainingMs, 3), // 毫秒三位数
  ].join(':')
}

// 消息列表
const messages = ref([])
const state = ref('PAUSE')
const recordSize = ref(0)

const webSocketManager = inject('webSocketManager') // 通过inject获取全局实例
const handleRecorderMessage = (status) => {
  if (state.value == 'PAUSE' && status.state != 'PAUSE' && messages.value.length > 0) {
    messages.value = []
  }
  recordSize.value = status.recordSize
  state.value = status.state
  messages.value.push(...status.messages)
}

onMounted(() => {
  // 订阅WebSocket频道
  webSocketManager.subscribe('/topic/recorder-message', handleRecorderMessage)
  request.post('/record/bind')
})
onUnmounted(() => {
  // 取消WebSocket订阅
  webSocketManager.unsubscribe('/topic/recorder-message')
  request.post('/record/unbind')
  state.value = 'PAUSE'
  messages.value = []
})
</script>

<style lang="less" scoped>
@import url('../assets/main.less');

.recording_container {
  padding: 0px 24px;
  border-radius: 12px;

  .title {
    color: var(--el-text-color-primary);
    font-size: 1.5em;
    margin-bottom: 1em;
    position: relative;
    margin-top: 10px;

    &::after {
      content: '';
      position: absolute;
      bottom: -8px;
      left: 0;
      width: 50px;
      height: 3px;
      background: @primary-color;
    }
  }

  .recorder_messages {
    width: 96%;
    height: calc(100vh - 280px);
    overflow-y: auto;
    border: 1px solid black;
    border-radius: 8px;
    padding: 8px;
    margin: auto;
  }

  .action_container {
  }
}
</style>
